/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.web.domain.support;

import org.vacoor.nothing.web.domain.Page;
import org.vacoor.nothing.web.domain.Pageable;
import org.vacoor.nothing.web.domain.Sort;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * 简单分页结果实现
 * 修改自 spring-data-common
 *
 * @author vacoor
 */
@SuppressWarnings("unused")
public class SimplePage<E> implements Page<E> {
    private static final long serialVersionUID = -7930126971384123318L;

    protected final Pageable pageable;
    protected final int recordCount;

    protected final List<E> data = new LinkedList<E>();

    public SimplePage(List<E> data) {
        this(null, data, data.size());
    }

    public SimplePage(Pageable pageable, List<E> data, int recordCount) {
        this.pageable = pageable;
        this.recordCount = recordCount;
        this.data.addAll(data);
    }

    /**
     * 获取页码, 如果没有设置 {@link Pageable} 则默认为第一页
     */
    @Override
    public int getPage() {
        return null == pageable ? 1 : pageable.getPage();
    }

    @Override
    public int getPageSize() {
        return null == pageable ? 0 : pageable.getPageSize();
    }

    @Override
    public Sort getSort() {
        return null == pageable ? null : pageable.getSort();
    }

    /**
     * 获取总页数, 如果构造时没有传入 {@link Pageable}, 则返回 1
     */
    @Override
    public int getTotalPages() {
        return getPageSize() == 0 ? 1 : (int) Math.ceil(getRecordCount() / 1.0 / getPageSize());
    }

    @Override
    public int getRecordCount() {
        return recordCount;
    }

    @Override
    public boolean hasPreviousPage() {
        return 1 < getPage();
    }

    @Override
    public boolean hasNextPage() {
        return getPage() < getTotalPages();
    }

    @Override
    public boolean isFirstPage() {
        return !hasPreviousPage();
    }

    @Override
    public boolean isLastPage() {
        return !hasNextPage();
    }

    @Override
    public List<E> getData() {
        return data;
    }

    @Override
    public Iterator<E> iterator() {
        return data.iterator();
    }

    @Override
    public Pageable nextPageable() {
        return isLastPage() ? null : new PageRequest(getPage() + 1, getPageSize(), getSort());
    }

    @Override
    public Pageable previousPageable() {
        return isFirstPage() ? null : new PageRequest(getPage() - 1, getPageSize(), getSort());
    }
}
